package com.openNetty.common.utils;

import com.openNetty.common.bean.ComRequest;
import com.openNetty.common.system.LoggerUtil;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpVersion;

import java.net.InetAddress;
import java.net.URI;
import java.util.Iterator;
import java.util.Map;

import static com.openNetty.common.bean.HttpInfo.*;

/**
 * @author zhenggm
 * @create 2017-11-17 上午 11:01
 **/


public class HttpMsgInit {

    private static LoggerUtil logger = LoggerUtil.getLogger(HttpMsgInit.class);

    /**
     * 组装HTTP请求
     *
     * @param req http请求类
     */
    public static DefaultFullHttpRequest setHttpMsg(ComRequest req) {
        URI uri = null;
        DefaultFullHttpRequest request = null;
        InetAddress address = null;
        try {
            address = InetAddress.getLocalHost();//获取的是本地的IP地址
            // 判断参数情况
            if (req.getMap() == null) {
                try {
                    uri = new URI("http://" + req.getBackNode().getAddress() + ":" + req.getBackNode().getPort() + "/sqlback?");
                    //logger.debug(uri.toASCIIString());
                    request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(req.getMethod()),
                            uri.toASCIIString(), Unpooled.wrappedBuffer(
                            EncryptUtil.DESedeEncByte(req.getHttpAck().getPass(), req.getMessage().getBytes("UTF-8"))));
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error(e);
                }
                // 构建http请求
                request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
                request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes());
                request.headers().set(HttpHeaders.Names.ACCEPT, "*/* \\r\\n");
                request.headers().set(HttpHeaders.Names.HOST, address.getAddress());
                request.headers().set(FILEPOSITION, req.getHttpAck().getPostition());
                request.headers().set(MEMCOUNT, req.getHttpAck().getCount());
                request.headers().set(FILENAME, req.getHttpAck().getFileName());
                request.headers().set(KEY, req.getHttpAck().getKey());
            } else {
                // 带参数情况下
                Iterator it = req.getMap().entrySet().iterator();
                try {
                    StringBuffer sb = new StringBuffer();
                    sb.append("http://" + req.getBackNode().getAddress() + ":" + req.getBackNode().getPort() + "/sqlback?");
                    while (it.hasNext()) {
                        Map.Entry entry = (Map.Entry) it.next();
                        sb.append(entry.getKey().toString()).append("=").append(entry.getValue().toString()).append("&");
                    }
                    sb.deleteCharAt(sb.length() - 1);
                    uri = new URI(sb.toString());
                    logger.debug(uri.toASCIIString());
                    request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(req.getMethod()),
                            uri.toASCIIString(), Unpooled.wrappedBuffer(
                            EncryptUtil.DESedeEncByte(req.getHttpAck().getPass(), req.getMessage().getBytes("UTF-8"))));
                } catch (Exception e) {
                    logger.error(e);
                }
                // 构建http请求
                request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
                request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes());
                request.headers().set(HttpHeaders.Names.ACCEPT, "*/* \\r\\n");
                request.headers().set(HttpHeaders.Names.HOST, address.getAddress());
                request.headers().set(FILEPOSITION, req.getHttpAck().getPostition());
                request.headers().set(MEMCOUNT, req.getHttpAck().getCount());
                request.headers().set(FILENAME, req.getHttpAck().getFileName());
                request.headers().set(KEY, req.getHttpAck().getKey());
            }
        } catch (Exception e) {
            logger.error(e);
        }
        return request;
    }
}
